#include<unistd.h>
#include<iostream>
#include<string.h>
#include <arpa/inet.h>
using namespace std;

int main(){
    // 创建客户端套接字
    int fd = socket(AF_INET, SOCK_STREAM, 0);
    if (fd == -1) {
        std::cerr << "Error creating client socket." << std::endl;
        return -1;
    }

    // 设置服务器地址结构
    sockaddr_in serverAddr;
    serverAddr.sin_family = AF_INET;
    inet_pton(AF_INET, "127.0.0.1", &serverAddr.sin_addr);
    serverAddr.sin_port = htons(9990);

    // 连接到服务器
    if (connect(fd, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) == -1) {
        std::cerr << "Error connecting to server." << std::endl;
        close(fd);
        return -1;
    }

    //通信
    char recvbuf[1024];
    while(true){
        const char* data="hello,i am client";
        //给客户端发送数据
        send(fd,data,strlen(data),0);
        cout<<"send data to server:"<<data<<endl;

        int len=recv(fd,recvbuf,sizeof(recvbuf),0);

        if(len==-1){
            cout<<"client read error"<<endl;
            exit(-1);
        }else {
            cout<<"client read data="<<recvbuf<<endl;
        }
        sleep(1);
    }
    close(fd);

    return 0;
}